/**
 * Created With IntelliJ IDEA
 * Description:牛客网：BM68 矩阵的最小路径和
 * <a href="https://www.nowcoder.com/practice/7d21b6be4c6b429bb92d219341c4f8bb?tpId=295&tqId=1009012&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj">...</a>
 * User: DELL
 * Data: 2022-11-05
 * Time: 22:45
 */

//动态规划
public class Solution {
    /**
     *
     * @param matrix int整型二维数组 the matrix
     * @return int整型
     */
    public int minPathSum (int[][] matrix) {
        //题目中规定数组不会为空，因此不需要进行判空处理
        int row = matrix.length;
        int col = matrix[0].length;
        //dp[i][j]表示以当前i，j位置为终点的最下路径和
        int[][] dp = new int[row][col];
        dp[0][0] = matrix[0][0];
        //处理第一行
        for (int i = 1; i < col; i++) {
            dp[0][i] = dp[0][i - 1] + matrix[0][i];
        }
        //处理第一列
        for (int i = 1; i < row; i++) {
            dp[i][0] = dp[i - 1][0] + matrix[i][0];
        }
        //处理剩余元素
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                dp[i][j] = Math.min(dp[i - 1][j],dp[i][j - 1]) + matrix[i][j];
            }
        }
        return dp[row - 1][col - 1];
    }
}
